from django.db import transaction
from django.db.models import F

from core.mixin.managers import CustomManager
from expense.query import PayCategoryQuerySet, ExpenseQuerySet


class PayCategoryManager(CustomManager):

    def get_queryset(self):
        return PayCategoryQuerySet(self.model, using=self._db)

    def move(self, obj, new_sort):
        qs = self.get_queryset().pay_type(obj.pay_type)
        with transaction.atomic():
            if obj.sort > new_sort:
                qs = qs.filter(sort__lt=obj.sort,
                               sort__gte=new_sort)
                qs.update(sort=F('sort') + 1)
            else:
                qs.filter(sort__lte=new_sort,
                          sort__gt=obj.sort).update(sort=F('sort') - 1)
            obj.sort = new_sort
            obj.save()


class ExpenseManager(CustomManager):

    def get_queryset(self):
        return ExpenseQuerySet(self.model, using=self._db)
